import sys
import asyncio
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget
from PyQt5.QtCore import QThread, pyqtSignal
import concurrent.futures

class AsyncWorker(QThread):
    """异步任务执行线程"""
    result_ready = pyqtSignal(str)  # 结果信号

    def run(self):
        """线程启动时执行"""
        loop = asyncio.new_event_loop()  # 创建独立事件循环
        asyncio.set_event_loop(loop)
        try:
            # 运行协程并获取结果
            result = loop.run_until_complete(self.async_task())
            self.result_ready.emit(result)
        finally:
            loop.close()

    async def async_task(self):
        """模拟异步操作（如网络请求）"""
        await asyncio.sleep(3)  # 非阻塞等待3秒
        return "异步任务完成！"

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.init_ui()
        self.thread = None

    def init_ui(self):
        self.setWindowTitle("协程+PyQt示例")
        self.button = QPushButton("启动异步任务")
        self.button.clicked.connect(self.start_task)
        
        layout = QVBoxLayout()
        layout.addWidget(self.button)
        container = QWidget()
        container.setLayout(layout)
        self.setCentralWidget(container)

    def start_task(self):
        """启动异步任务"""
        if self.thread is None or not self.thread.isRunning():
            self.thread = AsyncWorker()
            self.thread.result_ready.connect(self.on_task_done)
            self.thread.start()

    def on_task_done(self, result):
        """处理异步结果"""
        print(result)
        self.button.setEnabled(True)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())